//
//  AppDelegate.m
//  SanYiTeaching
//
//  Created by 李文强 on 2019/4/2.
//  Copyright © 2019 李文强. All rights reserved.
//

#import "AppDelegate.h"
#import "MainNavigationController.h"
#import "ViewController.h"
#import "LoginViewController.h"
#import "XGPush.h"
//#import <TICSDK/TICSDK.h>
#import "ChengJiYiChangVC.h"
#import "XGMessageModelOfMe.h"
#import "SYKaoQinYiChangViewController.h"
#import "SYHouSanMingViewController.h"

#import "CHAlertView.h"

#import "AppDelegate+TXIM.h"

#import <Bugly/Bugly.h>

#import "WXApi.h"

#import "CuoTiLvVC.h"
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
#import <UserNotifications/UserNotifications.h>
#endif

static NSString * const weixinAppID = @"wx3e7236909cdf1039";//微信appid(友盟分享)
static NSString * const weixinAppSecret = @"e6ac1a1ea90514112b600953566ebb02";//微信appSecret(友盟分享)
static NSString * const umengAppKey = @"5eb8fa8e570df3b1e80004cb";//友盟appkey

@interface AppDelegate ()<XGPushDelegate,RCIMUserInfoDataSource,RCIMGroupInfoDataSource,RCIMConnectionStatusDelegate,RCIMReceiveMessageDelegate,/*TIMUserStatusListener,TIMMessageListener,TIMConnListener,*/CHAlertViewDelegate>

@property (copy, nonatomic, nullable, readonly) NSString *deviceTokenString;
@property (nonatomic, strong) ChengJiYiChangVC *loginHomePageVC;
@property (nonatomic, strong) SYKaoQinYiChangViewController *kqycVC;
/**
 错题率
 */
@property (nonatomic, strong) CuoTiLvVC *cuoTiLvView;
@property (nonatomic, strong) SYHouSanMingViewController *hsmVC;
@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    // Override point for customization after application launch.
    self.window.backgroundColor = [UIColor whiteColor];
//    [[UINavigationBar appearance] setBarTintColor:[UIColor whiteColor]];
//    [[UINavigationBar appearance] setShadowImage:[[UIImage alloc] init]];
    
    [IQKeyboardManager sharedManager].shouldResignOnTouchOutside = YES;
    
    [IQKeyboardManager sharedManager].enableAutoToolbar = NO;
    
    [IQKeyboardManager sharedManager].enable = YES;
    
    [self setGuideViewWithUIWindow:self.window];
    
    [self.window makeKeyAndVisible];
    
    [self remoteNoticeApplication:application didFinishLaunchingWithOptions:launchOptions];

    [self configureRCIMSDK];

    [self initTICSDK];

    [self requestRCToken];
//初始化腾讯imsdk
    [self initTXIMSdk];
    //判断版本升级
    [self checkVersion];
    
    [Bugly startWithAppId:@"597dbd4b04"];
    
    [WXApi registerApp:weixinAppID enableMTA:YES];
//    [WXApi registerApp:@"wx3e7236909cdf1039" universalLink:@"https://SanYiTeaching.test.myTest/"];

    [self initUMSoial];

    return YES;
}
- (void)initUMSoial {
        
    /** 设置是否在console输出sdk的log信息.
     @param bFlag 默认NO(不输出log); 设置为YES, 输出可供调试参考的log信息. 发布产品时必须设置为NO.
     */
    [UMConfigure setLogEnabled:YES];
    
    [UMConfigure initWithAppkey:umengAppKey channel:@"App Store"];
    
    /* 设置微信的appKey和appSecret */
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatSession appKey:weixinAppID appSecret:weixinAppSecret redirectURL:@"http://mobile.umeng.com/social"];
}
// 初始化SDK
- (void)initTICSDK {
    //    [[TIMManager sharedInstance] setConnListener:self];
    //    [[TIMManager sharedInstance] setMessageListener:self];
   
    
}
//设置引导页面
- (void)setGuideViewWithUIWindow:(UIWindow *)window{

    
    if ([SYLoginUserModel sharedSYLoginUserModel].isLogin) {
        ViewController *loginHomePageVC = [[ViewController alloc] init];
        MainNavigationController *nav = [[MainNavigationController alloc]initWithRootViewController:loginHomePageVC];
        self.window.rootViewController = nav;
    } else {
        LoginViewController *login = [[LoginViewController alloc]init];
        self.window.rootViewController = [[UINavigationController alloc]initWithRootViewController:login];

    }
    [self.window makeKeyAndVisible];
    

//    //测试添加
//    ChengJiYiChangVC *loginHomePageVC = [[ChengJiYiChangVC alloc] init];
//    loginHomePageVC.view.frame = CGRectMake(0, 0, APP_WIDTH, APP_HEIGHT);
//    XGMessageModelOfMe *model = [[XGMessageModelOfMe alloc]init];
//    model.msgId = @"757";
//    loginHomePageVC.model = model;
//    [[UIApplication sharedApplication].keyWindow.rootViewController.view addSubview:loginHomePageVC.view];

}
#pragma mark - TIMUserStatusListener
/**
 *  踢下线通知
 */
- (void)onForceOffline {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"账号被踢" message:nil preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [(UINavigationController *)self.window.rootViewController popToRootViewControllerAnimated:YES];
    }];
    [alert addAction:action];
    UIViewController *currentVC = ((UINavigationController *)self.window.rootViewController).topViewController;
    [currentVC presentViewController:alert animated:YES completion:nil];
    
}
#pragma mark ----- 融云单聊初始化 ----
- (void)configureRCIMSDK {
    
    self.friendsArray = [[NSMutableArray alloc]init];
    self.groupsArray = [[NSMutableArray alloc]init];
    self.AllArray = [NSMutableArray array];
    [[RCIM sharedRCIM] initWithAppKey:@"uwd1c0sxuqle1"];
    [[RCIM sharedRCIM] setUserInfoDataSource:self];
    [[RCIM sharedRCIM] setGroupInfoDataSource:self];
    [[RCIM sharedRCIM] setConnectionStatusDelegate:self];
    [[RCIM sharedRCIM] setReceiveMessageDelegate:self];
    [RCIM sharedRCIM].enableTypingStatus = YES;
    [RCIM sharedRCIM].enableMessageAttachUserInfo = YES;
    [RCIM sharedRCIM].enablePersistentUserInfoCache = NO;
    [RCIM sharedRCIM].isMediaSelectorContainVideo = YES;
}
#pragma mark --- 融云聊天 --
/** 获取融云token 连接服务器*/

- (void)requestRCToken {
    NSString *trToken = [USERDEFAL objectForKey:RYTokenDefalut];
    NSString *imid = [USERDEFAL objectForKey:RYUserIdDefalut];
    NSString *name = [USERDEFAL objectForKey:RYUserNameDefalut];
    NSString *headPath = [USERDEFAL objectForKey:RYUserPathDefalut];

    [[RCIM sharedRCIM] connectWithToken:trToken     success:^(NSString *userId) {
                NSLog(@"登陆成功。当前登录的用户ID：%@", userId);
//                [LoginRecord shareInstance].RCUserID = userId;
    [[RYChatManager shareManager]loginRongCloudWithUserInfo:[[RCUserInfo alloc]initWithUserId:imid name:name portrait:headPath] withToken:trToken];
        
            } error:^(RCConnectErrorCode status) {
                
                NSLog(@"登陆的错误码为:%ld", (long)status);
                
            } tokenIncorrect:^{
                
                NSLog(@"token错误1 过期或者不正确");
                NSString *userIdS;
            }];

}

//融云账号监测
- (void)onRCIMConnectionStatusChanged:(RCConnectionStatus)status {
    if (status == ConnectionStatus_KICKED_OFFLINE_BY_OTHER_CLIENT) {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"您的帐号在别的设备上登录，您被迫下线！" delegate:nil cancelButtonTitle:@"知道了" otherButtonTitles:nil, nil];
        [alert show];
        

//        [LoginRecord shareInstance].token = nil;
    } else if (status == ConnectionStatus_TOKEN_INCORRECT) {
        [self requestRCToken];
    }
}
-(void)alertViewDidClickButtonWithIndex:(NSInteger)index{
    
    if (index == 1) {
        [USERDEFAL removeObjectForKey:PassDefalut];
        [USERDEFAL removeObjectForKey:TokenDefalut];
        [USERDEFAL removeObjectForKey:RYUserPathDefalut];
        [USERDEFAL removeObjectForKey:RYUserNameDefalut];
        [USERDEFAL removeObjectForKey:RYUserIdDefalut];
        [USERDEFAL removeObjectForKey:RYTokenDefalut];
        [USERDEFAL removeObjectForKey:RYIMidIDDefalut];
        [self.friendsArray removeAllObjects];
        [self.groupsArray removeAllObjects];
        [self.AllArray removeAllObjects];
        [[RCIMClient sharedRCIMClient] disconnect];
        
        LoginViewController *login = [[LoginViewController alloc]init];
        [UIApplication sharedApplication].keyWindow.rootViewController = [[UINavigationController alloc]initWithRootViewController:login];
        [[UIApplication sharedApplication].keyWindow makeKeyAndVisible];
    }
}
//是否有融云未读聊天消息
- (void)onRCIMReceiveMessage:(RCMessage *)message left:(int)left {
    int unreadMsgCount = [[RCIMClient sharedRCIMClient] getUnreadCount:@[@(ConversationType_PRIVATE),@(ConversationType_DISCUSSION),@(ConversationType_APPSERVICE),@(ConversationType_PUBLICSERVICE),@(ConversationType_GROUP)]];
    NSString * unreadNum = [NSString stringWithFormat:@"%d",unreadMsgCount];
//    [LoginRecord shareInstance].myMsgNum = unreadNum.intValue;
    if (!(unreadNum.intValue == 0)) { //显示
        
//        [self.tabBarVC.tabBar showBadgeOnItemIndex:4];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"IsHaveRongYuNotification" object:self userInfo:nil];
        
    } else { //隐藏
        
//        [self.tabBarVC.tabBar hideBadgeOnItemIndex:4];
    }
}

//获取融云单聊信息
- (void)getUserInfoWithUserId:(NSString *)userId completion:(void (^)(RCUserInfo *))completion {
    NSLog(@"融云获取信息userId==>%@",userId);
    RCUserInfo *user = [[RCUserInfo alloc]init];
    NSString *imid = [USERDEFAL objectForKey:RYUserIdDefalut];
    NSString *name = [USERDEFAL objectForKey:RYUserNameDefalut];
    NSString *headPath = [USERDEFAL objectForKey:RYUserPathDefalut];
    user.userId = userId;
    if ([userId isEqualToString:imid]) {
        user.name = name;
        user.portraitUri  = headPath;
        [RCIM sharedRCIM].currentUserInfo = user;
    } else {
        for (NSInteger i = 0; i<self.friendsArray.count; i++) {
            RCUserInfo *aUser = self.friendsArray[i];
            if ([userId isEqualToString:aUser.userId]) {
                completion(aUser);
                break;
            }
        }
    }
    return completion(user);
}
//获取融云群聊信息
- (void)getGroupInfoWithGroupId:(NSString *)groupId completion:(void (^)(RCGroup *))completion {
    
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    NSInteger ToatalunreadMsgCount = (NSInteger)[[RCIMClient sharedRCIMClient] getUnreadCount:@[@(ConversationType_PRIVATE),@(ConversationType_DISCUSSION),@(ConversationType_GROUP),@(ConversationType_CHATROOM)]];
    [UIApplication sharedApplication].applicationIconBadgeNumber = ToatalunreadMsgCount;
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    [[NSNotificationCenter defaultCenter] postNotificationName:@"SYApplicationWillTerminate" object:nil];
    
}

#pragma mark - 推送
- (void)remoteNoticeApplication:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
    [[XGPush defaultManager] setEnableDebug:YES];
    XGNotificationAction *action1 = [XGNotificationAction actionWithIdentifier:@"xgaction001" title:@"xgAction1" options:XGNotificationActionOptionNone];
    XGNotificationAction *action2 = [XGNotificationAction actionWithIdentifier:@"xgaction002" title:@"xgAction2" options:XGNotificationActionOptionDestructive];
    if (action1 && action2) {
        XGNotificationCategory *category = [XGNotificationCategory categoryWithIdentifier:@"xgCategory" actions:@[action1, action2] intentIdentifiers:@[] options:XGNotificationCategoryOptionNone];
        
        XGNotificationConfigure *configure = [XGNotificationConfigure configureNotificationWithCategories:[NSSet setWithObject:category] types:XGUserNotificationTypeAlert|XGUserNotificationTypeBadge|XGUserNotificationTypeSound];
        if (configure) {
            [[XGPush defaultManager] setNotificationConfigure:configure];
        }
    }
    
    //[XGPushStat setIDFA:@"testidfa"];
    [[XGPush defaultManager] startXGWithAppID:AccessID appKey:AccessKey delegate:self];
    
//    NSInteger number = [[XGPush defaultManager] xgApplicationBadgeNumber];
//    [[XGPush defaultManager] setXgApplicationBadgeNumber:number+1];
    if ([XGPush defaultManager].xgApplicationBadgeNumber > 0) {
        [[XGPush defaultManager] setXgApplicationBadgeNumber:0];
    }
    [[XGPush defaultManager] reportXGNotificationInfo:launchOptions];
}
/**
 统一收到通知消息的回调
 @param notification 消息对象
 @param completionHandler 完成回调
 @note SDK 3.2.0+
 */
- (void)xgPushDidReceiveRemoteNotification:(id)notification withCompletionHandler:(void (^)(NSUInteger))completionHandler {
    
    if ([notification isKindOfClass:[NSDictionary class]]) {
        [[XGPush defaultManager] reportXGNotificationInfo:(NSDictionary *)notification];
         NSLog(@"收到消息%@",(NSDictionary *)notification);
        
        completionHandler(UIBackgroundFetchResultNewData);
    } else if ([notification isKindOfClass:[UNNotification class]]) {
        if (@available(iOS 10.0, *)) {
            [[XGPush defaultManager] reportXGNotificationInfo:((UNNotification *)notification).request.content.userInfo];
            
            NSLog(@"收到消息%@",((UNNotification *)notification).request.content.userInfo);
            
        } else {
            // Fallback on earlier versions
        }
        if (@available(iOS 10.0, *)) {
            completionHandler(UNNotificationPresentationOptionBadge | UNNotificationPresentationOptionSound | UNNotificationPresentationOptionAlert);
        } else {
            // Fallback on earlier versions
        }
    }
   
}
#pragma mark - 异常处理
- (void)chuLiMessage:(XGMessageModelOfMe *)model{
    if ([model.type isEqualToString:@"101"]) {
        //考勤异常
        
        _kqycVC = [[SYKaoQinYiChangViewController alloc] init];
        _kqycVC.view.frame = CGRectMake(0, 0, APP_WIDTH, APP_HEIGHT);
        _kqycVC.xgModel = model;
        [_kqycVC requestDataListArr];
        [[UIApplication sharedApplication].keyWindow.rootViewController.view addSubview:_kqycVC.view];
    }else if ([model.type isEqualToString:@"102"]){
        //排名异常
        _loginHomePageVC = [[ChengJiYiChangVC alloc] init];
        _loginHomePageVC.view.frame = CGRectMake(0, 0, APP_WIDTH, APP_HEIGHT);
        _loginHomePageVC.model = model;
        [_loginHomePageVC getPaiMingChengJiYiChangUp];
        [_loginHomePageVC getPaiMingChengJiYiChangDown];
        [[UIApplication sharedApplication].keyWindow.rootViewController.view addSubview:_loginHomePageVC.view];
    }else if ([model.type isEqualToString:@"103"]){
        //错题率
//        [XSInfoView showInfo:@"此功能正在开发中..." onView:[UIApplication sharedApplication].keyWindow.rootViewController];
        //错题率
        _cuoTiLvView = [[CuoTiLvVC alloc]init];
        _cuoTiLvView.msgId = model.msgId;
        [_cuoTiLvView getRequest];
        [[UIApplication sharedApplication].keyWindow.rootViewController.view addSubview:_cuoTiLvView.view];
    }else if ([model.type isEqualToString:@"104"]){
        //成绩后三名
        _hsmVC = [[SYHouSanMingViewController alloc] init];
        _hsmVC.view.frame = CGRectMake(0, 0, APP_WIDTH, APP_HEIGHT);
        _hsmVC.xgModel = model;
        [_hsmVC requestData];
        [[UIApplication sharedApplication].keyWindow.rootViewController.view addSubview:_hsmVC.view];
    }
}
#pragma 字符串转换成字典
NSDictionary *dictionaryWithJsonString(NSString *jsonString)
{
    if (jsonString == nil) {
        return nil;
    }
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&err];
    if(err) {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}
/**
 收到推送的回调
 @param application  UIApplication 实例
 @param userInfo 推送时指定的参数
 @param completionHandler 完成回调
 */
- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
    [[XGPush defaultManager] reportXGNotificationInfo:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}
// iOS 10 新增回调 API
// App 用户点击通知
// App 用户选择通知中的行为
// App 用户在通知中心清除消息
// 无论本地推送还是远程推送都会走这个回调
#if __IPHONE_OS_VERSION_MAX_ALLOWED >=     __IPHONE_10_0
- (void)xgPushUserNotificationCenter:(UNUserNotificationCenter *)center
      didReceiveNotificationResponse:(UNNotificationResponse *)response
               withCompletionHandler:(void (^)(void))completionHandler
API_AVAILABLE(ios(10.0)){
    
    if (@available(iOS 10.0, *)) {
        [[XGPush defaultManager] reportXGNotificationResponse:response];
    } else {
        // Fallback on earlier versions
    }
    completionHandler();
    NSDictionary *dicString = [NSDictionary new];
    dicString = ((UNNotification *)response.notification).request.content.userInfo;
    NSString *dataString = [dicString objectForKey:@"subtitle"];
    NSDictionary *paramaDic = dictionaryWithJsonString(dataString);
    NSLog(@"得到的参数DIC %@   /n/n %@",paramaDic,dicString);
    XGMessageModelOfMe *model = [XGMessageModelOfMe yy_modelWithJSON:paramaDic];
    [self chuLiMessage:model];
    // 清除角标
    if ([XGPush defaultManager].xgApplicationBadgeNumber > 0) {
        [[XGPush defaultManager] setXgApplicationBadgeNumber:0];
    }
}

// App 在前台弹通知需要调用这个接口
- (void)xgPushUserNotificationCenter:(UNUserNotificationCenter *)center
             willPresentNotification:(UNNotification *)notification
               withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler
API_AVAILABLE(ios(10.0)){
    [[XGPush defaultManager] reportXGNotificationInfo:notification.request.content.userInfo];
    if (@available(iOS 10.0, *)) {
        completionHandler(UNNotificationPresentationOptionBadge | UNNotificationPresentationOptionSound | UNNotificationPresentationOptionAlert);
    } else {
        // Fallback on earlier versions
    }

}
#endif

#pragma mark - debug下
/**
 @brief 监控信鸽推送服务地启动情况
 
 @param isSuccess 信鸽推送是否启动成功
 @param error 信鸽推送启动错误的信息
 */
- (void)xgPushDidFinishStart:(BOOL)isSuccess error:(nullable NSError *)error{
    NSLog(@"错误 %@",error);
}

/**
 @brief 向信鸽服务器注册设备token的回调
 
 @param deviceToken 当前设备的token
 @param error 错误信息
 @note 当前的token已经注册过之后，将不会再调用此方法
 */ 
- (void)xgPushDidRegisteredDeviceToken:(nullable NSString *)deviceToken error:(nullable NSError *)error{
    NSLog(@"推送token %@",deviceToken);
    NSLog(@"错误 %@",error);
}

/**
 注册通知失败

 @param application application
 @param error 错误
 */
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    NSLog(@"[XGDemo] register APNS fail.\n[XGDemo] reason : %@", error);
    [[NSNotificationCenter defaultCenter] postNotificationName:@"registerDeviceFailed" object:nil];
}


/**
 强制竖屏
 @return 根据allowAcrolls字段来判断是否需要横屏
 */
//- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {
//    
//        return UIInterfaceOrientationMaskLandscapeLeft|UIInterfaceOrientationMaskLandscapeRight;
//}


#pragma mark - 检测是否需要版本更新
// 向服务器检测版本
- (void)checkVersion {
    
    NSString *ver = [[[NSBundle mainBundle]infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
    [mgr.responseSerializer setAcceptableContentTypes: [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil]];
    //POST必须上传的字段
    [mgr POST:@"http://itunes.apple.com/cn/lookup?id=1477025373" parameters:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
//        NSLog(@"%@",responseObject);
        NSArray *array = responseObject[@"results"];
        if (array.count != 0) {// 先判断返回的数据是否为空
            NSDictionary *dict = array[0];
            
//            NSLog(@"%@",dict);
//            NSLog(@"%@",dict[@"version"]);
            if (![dict[@"version"] isEqualToString:ver]) {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"发现新版本" message:[NSString stringWithFormat:@"发现最新版本:%@请下载在更新!",dict[@"version"]] delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
                [alert show];
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 1) {
        NSString * urlStr = [NSString stringWithFormat: @"itms-apps://itunes.apple.com/app/id%@?mt=8",@"1477025373"];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlStr]];
    }
}
@end
